/**
 * 上传用户头像
 */

const express = require('express')
const adminpic = express.Router()

// 导入数据库
const db = require('../../utils/db')

// 导入文件上传解析模块
const getformidable = require('../../utils/myformidable')
const fs = require('fs')

// 导入 ali-oss 上传本地文件
const myoss = require('../../utils/myoss')

// 获取头像
adminpic.get('/getadminpic', (req, res) => {
   const sql = `SELECT * FROM adminser`
   db.query(sql, async (err, result) => {
      res.json({pic: result})
   })
})

// 上传头像
adminpic.post('/setadminpic', async (req, res) => {
   const { files, params } = await getformidable(req)
   const { newFilename, size, filepath } = files.adminpic
   if (size > 0) {
      const sql = `INSERT INTO adminser(userpic) VALUES('${newFilename}')`
      db.query(sql, async (err, result) => {
         await myoss.pushdata(newFilename, filepath)
         fs.unlinkSync(filepath) // 删除本地logo文件
         res.redirect('/admin/list')
      })
   } else {
      res.end()
   }
})


module.exports = adminpic